<?php
/**
 * Create By: PhpStorm
 * User: yihua
 * File: DeleteGoodsCategory.php
 * Date: 2017/2/25
 * Time: 23:05
 */
namespace app\api\model\page\goods;

use app\api\model\dao\Goods;
use app\api\model\dao\GoodsCategory;
use app\library\Error;
use app\library\PageBase;
use think\Log;

class DeleteGoodsCategory extends PageBase
{
    private $objGoodsCategoryDao;

    public function __construct()
    {
        parent::__construct();
        $this->objGoodsCategoryDao = new GoodsCategory();
    }

    public function excute($param)
    {
        $ret = $this->checkParam($param);
        if ($ret) {
            return $this->getRes(Error::ERR_PARAM, $ret);
        }
        //查看此分类有没有子类
        $obj = new GoodsCategory();
        $ret = $obj->getGoodsCateGoryByConds(['parent_id' => $param['cat_id']]);
        //return gettype($ret);
        if (false === $ret) {
            return $this->getRes(Error::ERR_SYS);
        }
        if (count($ret)) {
            return $this->getRes(Error::ERR_GOODSCATEGORY_HAS_SUBCATEGORY);
        }

        //查看该分类下是否存在商品
        $objGoods = new Goods();
        $param['is_delete'] = 0;
        $ret = $objGoods->getCount($param);
        if ($ret) {
            return $this->getRes(Error::ERR_GOODSCATEGORY_HAS_GOODS);
        } else {
            try {
                $this->objGoodsCategoryDao->deleteGoodsCategory($param['cat_id']);
            } catch (Exception $e) {
                Log::error('GoodsCategory delete failed: ', $e->getMessage());
                return $this->getRes(Error::ERR_SYS);
            }
            return $this->getRes();
        }
    }

    public function checkParam($param)
    {
        $rule = [
            'cat_id' => 'require',
        ];
        $msg = [
            'cat_id.require' => 'cat_id必须',
        ];
        $validate = new \think\Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            return $validate->getError();
        }
        return '';
    }
}